# -*- coding: utf-8 -*-
import sys
if '..' not in sys.path:sys.path.append('..')
if '../..' not in sys.path:sys.path.append('../..')
from flask import *
from functools import wraps
from core.model import Device
from core.cache import redis
import datetime

static = Blueprint('static', __name__)

def staticfilesSetup(mimetype,model,prefix,identify,timefield):
    def decorator(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            filename = str(kwargs['filename'].split('.')[0])
            origintime = redis.hget(prefix+filename,timefield)
            if not origintime:
                try:
                    element = model.objects(**{identify:filename}).only(timefield).get()
                except model.DoesNotExist:
                    return abort(404)
                origintime = getattr(element,timefield)
                redis.hset(prefix+filename,timefield,origintime.strftime('%Y-%m-%d %H:%M:%S'))
            else:
                origintime = datetime.datetime.strptime(origintime,'%Y-%m-%d %H:%M:%S')
            if request.if_modified_since and request.if_modified_since >= origintime:
                return Response(status=304, headers=[('Content-Type',mimetype)])
            data = func(filename)
            response = Response(headers=[
                ('Content-Type',mimetype),
                # ('Cache-Control','public, max-age=216000'),
                ('Last-Modified',origintime.strftime('%a, %d %b %Y %H:%M:%S GMT')),
                # ('Expires','Fri, 01 Apr 2115 00:00:00 GMT'),
                # ('Content-Length',len(data)),
            ])
            response.data = data
            return response
        return wrapper
    return decorator

@static.route('/baby/portrait/<filename>', methods=['GET'])
@staticfilesSetup('image/png',Device,'Device:','imgkey','altertime')
def babyportrait(filename):
    portrait = redis.hget('Device:'+filename,'portrait')
    if not portrait:
        try:
            dev = Device.objects(imgkey=filename).only('portrait').get()
        except Device.DoesNotExist:
            return abort(404)
        try:
            portrait = dev.portrait.decode('base64')
        except:
            portrait = ''
        redis.hset('Device:'+filename,'portrait',portrait)
    return portrait

